package org.funtester.performance.books.chapter10.section3;

import org.apache.commons.pool2.impl.GenericObjectPool;
import org.apache.commons.pool2.impl.GenericObjectPoolConfig;
import org.funtester.performance.books.chapter06.section2.MySqlBase;

import java.sql.ResultSet;
import java.time.Duration;

public class MySqlPool {

    public static void main(String[] args) throws Exception {
        String url = "jdbc:mysql://127.0.0.1:3306/funtester";// 服务端地址
        String user = "root";// 用户名
        String password = "funtester";// 密码
        GenericObjectPool<MySqlBase> mySqlPool = initMySqlPool(url, user, password);// 初始化MySQL对象池
        MySqlBase base = mySqlPool.borrowObject();// 从对象池中获取MySQL对象
        ResultSet resultSet = base.statement.executeQuery("select * from user limit 3;");// 执行查询
        while (resultSet.next()) {// 遍历结果集
            System.out.println(resultSet.getString("id") + " " + resultSet.getString("name") + " " + resultSet.getString("age"));// 打印结果
        }
        mySqlPool.returnObject(base);// 归还MySQL对象
        mySqlPool.close();// 关闭对象池
    }

    /**
     * 初始化UserBehavior对象池
     *
     * @return
     */
    public static GenericObjectPool<MySqlBase> initMySqlPool(String url, String user, String password) {

        GenericObjectPoolConfig poolConfig = new GenericObjectPoolConfig();
        poolConfig.setMaxTotal(100);
        poolConfig.setMinIdle(10);
        poolConfig.setMaxIdle(20);
        poolConfig.setMaxWait(Duration.ofMillis(1000));
        poolConfig.setMinEvictableIdleTime(Duration.ofMillis(1000));
        poolConfig.setBlockWhenExhausted(true);
        poolConfig.setTimeBetweenEvictionRuns(Duration.ofMillis(1000));
        return new GenericObjectPool<>(new MySqlFactory(url, user, password), poolConfig);
    }

}
